﻿using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;

/// <summary>
/// 附着在与VR控制器交互的物体上
/// </summary>
public class VRControllerInteractive : MonoBehaviour {
    public SteamVR_TrackedController controller;
    public bool isHolding;


    public event Action StartHolding;
    public event Action ReleaseHolding;


    private void OnTriggerEnter(Collider other)
    {
        if(controller==null && other.tag==TagSet.VRController)
        {
            var controllerHolder = other.GetComponent<VRControllerHolder>();
            if(controllerHolder==null || !controllerHolder.isMonoHolding || controllerHolder.triggerInteractive==null)
            {
                controller = other.GetComponent<SteamVR_TrackedController>();
                controller.TriggerClicked += PressTrigger;
                controller.TriggerUnclicked += ReleaseTrigger;
                if(controllerHolder!=null) controllerHolder.triggerInteractive = this;
            }
            
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (controller!=null && !isHolding &&other.transform == controller.transform)
        {
            controller.TriggerClicked -= PressTrigger;
            controller.TriggerUnclicked -= ReleaseTrigger;
            controller = null;

            var controllerHolder = other.GetComponent<VRControllerHolder>();
            if (controllerHolder != null && controllerHolder.isMonoHolding && controllerHolder.triggerInteractive == this)
            {
                controllerHolder.triggerInteractive = null;
            }
        }
    }



    private void OnDisable()
    {
        if (controller != null)
        {
            var controllerHolder = controller.GetComponent<VRControllerHolder>();
            if (controllerHolder != null && !controllerHolder.isMonoHolding && controllerHolder.triggerInteractive == this)
            {
                controllerHolder.triggerInteractive = null;
            }

            controller.TriggerClicked -= PressTrigger;
            controller.TriggerUnclicked -= ReleaseTrigger;
            Release();
            controller = null;
        }
    }




    private void PressTrigger(object sender, ClickedEventArgs e)
    {
        if(controller!=null)
        {
            isHolding = true;
            if (StartHolding != null) StartHolding();
        }
        
    }

    private void ReleaseTrigger(object sender, ClickedEventArgs e)
    {
        Release();
    }

    public void Release()
    {
        if(ReleaseHolding!=null) ReleaseHolding();
        isHolding = false;
    }



}
